package com.cycplus.test.base

import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.viewbinding.ViewBinding
import com.cycplus.test.extensions.inflateBindingWithGeneric
import io.reactivex.functions.Consumer

abstract class BaseBindingFragment<VB : ViewBinding> : LazyFragment() {

    private var _binding: VB? = null
    protected val mBinding: VB get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = inflateBindingWithGeneric(inflater, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        initEvent()
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

    override fun lazyInit() {
        initData()
    }

    protected abstract fun initView(rootView: View)

    protected abstract fun initEvent()

    protected abstract fun initData()

    protected fun checkSelfPermission(
        permissions: List<String>,
        grantedCallback: Consumer<List<String>>,
        deniedCallback: Consumer<List<String>>
    ) {
        context?.apply {
            var result = true
            val grantedList = arrayListOf<String>()
            val deniedList = arrayListOf<String>()
            permissions.forEach {
                if (ContextCompat.checkSelfPermission(
                        this,
                        it
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    result = false
                    deniedList.add(it)
                } else {
                    grantedList.add(it)
                }
            }
            if (result) {
                grantedCallback.accept(grantedList)
            } else {
                deniedCallback.accept(deniedList)
            }
        } ?: run {
            throw java.lang.IllegalStateException("you must call this method after fragment has been attached to activity")
        }
    }
}